package com.sinodata.bsm.cicp.collector.windows;

import java.io.BufferedReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.IOUtils;

import com.sinodata.bsm.cicp.collector.Collector;
import com.sinodata.bsm.cicp.exception.CollectorException;
import com.sinodata.bsm.cicp.util.WmiUtil;
import com.sinodata.bsm.common.vo.ResPropertyValue;

/**
 * 
 * <p>
 * Description: 通过调用wmi中的GetProcessor.vbs获取windows进程的信息
 * 
 * </p>
 *
 * @author wangpeng
 * @version 1.0

 * <p>
 * History: 
 *
 * Date                     Author         Version     Description
 * ---------------------------------------------------------------------------------
 * 2012-8-8 下午10:19:12          wangpeng        1.0         To create
 * </p>
 *
 * @since 
 * @see
 */
public class WinSingleProc extends Collector {

    @Override
    public List<ResPropertyValue> collect(String ip) throws CollectorException {
        List<ResPropertyValue> values = new ArrayList<ResPropertyValue>();
        String[] propMetas = getPropMeta();
        String proName = this.paramMap.get("Process Name").trim();//进程名
        String separetor = " <@> ";
        BufferedReader br = null;
        String strLine = null;
        try {
            br = WmiUtil.execWmiScript(ip, "GetProcessor.vbs", new String[] { proName });
            while ((strLine = br.readLine()) != null) {
                if (strLine.indexOf(separetor) > -1) {
                    String[] temp = strLine.split(separetor);
                    if (temp.length != 4) {
                        return null;
                    }
                    if (temp[0].startsWith(".")) {
                        temp[0] = "0" + temp[0];
                    }
                    ResPropertyValue propertyValueX = new ResPropertyValue();
                    ResPropertyValue.PropValue[] propValues = new ResPropertyValue.PropValue[propMetas.length];
                    propValues[0] = ResPropertyValue.createPropValue(temp[0], propMetas[0]);
                    propValues[1] = ResPropertyValue.createPropValue(temp[1], propMetas[1]);
                    propValues[2] = ResPropertyValue.createPropValue(temp[2], propMetas[2]);
                    propValues[3] = ResPropertyValue.createPropValue(temp[3], propMetas[3]);
                    propertyValueX.setValues(propValues);
                    values.add(propertyValueX);
                }
            }
        } catch (Exception ex) {
            logger.error("failed to call " + this.getClass().getName() + ".collect()", ex);
            throw new CollectorException(ex);
        } finally {
            IOUtils.closeQuietly(br);
        }
        return values;
    }

    @Override
    public String[] getParamMeta() {
        return new String[] { "Process Name" };
    }

    @Override
    public String[] getPropMeta() {
        return new String[] { "$1", "$2", "$3", "$4" };
    }
}
